import React, { useEffect, useState } from 'react'
import { Alert, Collapse, Typography, Space, Tag, Button } from 'antd'
import {
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  BugOutlined,
} from '@ant-design/icons'
import { validateSQL } from '@/utils'

const { Panel } = Collapse
const { Text, Paragraph } = Typography

interface SQLError {
  type: 'error' | 'warning' | 'info'
  message: string
  line?: number
  column?: number
  suggestion?: string
}

interface SQLValidatorProps {
  sql: string
  onValidationChange?: (isValid: boolean, errors: SQLError[]) => void
  showDetails?: boolean
  autoValidate?: boolean
}

const SQLValidator: React.FC<SQLValidatorProps> = ({
  sql,
  onValidationChange,
  showDetails = true,
  autoValidate = true,
}) => {
  const [errors, setErrors] = useState<SQLError[]>([])
  const [isValid, setIsValid] = useState(true)
  const [isValidating, setIsValidating] = useState(false)

  // 高级SQL验证函数
  const validateSQLAdvanced = (sqlText: string): { valid: boolean; errors: SQLError[] } => {
    const errors: SQLError[] = []
    const trimmedSQL = sqlText.trim()

    if (!trimmedSQL) {
      return { valid: true, errors: [] }
    }

    // 基础语法检查
    const basicValidation = validateSQL(trimmedSQL)
    if (!basicValidation.valid) {
      errors.push(...basicValidation.errors.map(error => ({
        type: 'error' as const,
        message: error,
        suggestion: '请检查SQL语法是否正确'
      })))
    }

    // 检查SQL语句类型
    const upperSQL = trimmedSQL.toUpperCase()
    const sqlStatements = trimmedSQL.split(';').filter(stmt => stmt.trim())

    sqlStatements.forEach((statement, index) => {
      const trimmedStmt = statement.trim().toUpperCase()
      if (!trimmedStmt) return

      // 检查危险操作
      const dangerousOperations = [
        { keyword: 'DROP TABLE', level: 'error' as const, message: '检测到DROP TABLE操作，这将删除整个表' },
        { keyword: 'DROP DATABASE', level: 'error' as const, message: '检测到DROP DATABASE操作，这将删除整个数据库' },
        { keyword: 'TRUNCATE', level: 'warning' as const, message: '检测到TRUNCATE操作，这将清空表数据' },
        { keyword: 'DELETE FROM', level: 'warning' as const, message: '检测到DELETE操作，请确保有WHERE条件' },
        { keyword: 'UPDATE', level: 'warning' as const, message: '检测到UPDATE操作，请确保有WHERE条件' },
      ]

      dangerousOperations.forEach(op => {
        if (trimmedStmt.includes(op.keyword)) {
          errors.push({
            type: op.level,
            message: op.message,
            suggestion: op.level === 'error' ? '建议在测试环境中执行' : '建议添加WHERE条件限制影响范围'
          })
        }
      })

      // 检查SELECT语句的最佳实践
      if (trimmedStmt.startsWith('SELECT')) {
        // 检查是否使用SELECT *
        if (trimmedStmt.includes('SELECT *')) {
          errors.push({
            type: 'info',
            message: '建议避免使用SELECT *，明确指定需要的列',
            suggestion: '使用具体的列名可以提高查询性能'
          })
        }

        // 检查是否缺少LIMIT
        if (!trimmedStmt.includes('LIMIT') && !trimmedStmt.includes('TOP')) {
          errors.push({
            type: 'info',
            message: '建议在SELECT语句中添加LIMIT子句',
            suggestion: '添加LIMIT可以避免返回过多数据'
          })
        }

        // 检查JOIN语句
        if (trimmedStmt.includes('JOIN') && !trimmedStmt.includes('ON')) {
          errors.push({
            type: 'warning',
            message: 'JOIN语句缺少ON条件',
            suggestion: '请添加适当的JOIN条件'
          })
        }
      }

      // 检查INSERT语句
      if (trimmedStmt.startsWith('INSERT')) {
        if (!trimmedStmt.includes('VALUES') && !trimmedStmt.includes('SELECT')) {
          errors.push({
            type: 'error',
            message: 'INSERT语句缺少VALUES或SELECT子句',
            suggestion: '请添加要插入的数据'
          })
        }
      }

      // 检查UPDATE语句
      if (trimmedStmt.startsWith('UPDATE')) {
        if (!trimmedStmt.includes('SET')) {
          errors.push({
            type: 'error',
            message: 'UPDATE语句缺少SET子句',
            suggestion: '请指定要更新的列和值'
          })
        }
        if (!trimmedStmt.includes('WHERE')) {
          errors.push({
            type: 'warning',
            message: 'UPDATE语句缺少WHERE条件，将更新所有行',
            suggestion: '建议添加WHERE条件限制更新范围'
          })
        }
      }

      // 检查DELETE语句
      if (trimmedStmt.startsWith('DELETE')) {
        if (!trimmedStmt.includes('WHERE')) {
          errors.push({
            type: 'warning',
            message: 'DELETE语句缺少WHERE条件，将删除所有行',
            suggestion: '建议添加WHERE条件限制删除范围'
          })
        }
      }
    })

    // 检查性能相关问题
    const performanceChecks = [
      {
        pattern: /LIKE\s+['"]%.*%['"]/gi,
        message: '使用前后通配符的LIKE查询可能导致性能问题',
        type: 'info' as const,
        suggestion: '考虑使用全文搜索或其他索引策略'
      },
      {
        pattern: /ORDER\s+BY\s+RAND\(\)/gi,
        message: 'ORDER BY RAND()在大表上性能较差',
        type: 'warning' as const,
        suggestion: '考虑使用其他随机排序方法'
      },
      {
        pattern: /SELECT\s+DISTINCT/gi,
        message: 'DISTINCT操作可能影响性能',
        type: 'info' as const,
        suggestion: '确保真的需要去重，考虑使用GROUP BY'
      },
    ]

    performanceChecks.forEach(check => {
      if (check.pattern.test(trimmedSQL)) {
        errors.push({
          type: check.type,
          message: check.message,
          suggestion: check.suggestion
        })
      }
    })

    return {
      valid: errors.filter(e => e.type === 'error').length === 0,
      errors
    }
  }

  // 执行验证
  const performValidation = async () => {
    if (!autoValidate || !sql.trim()) {
      setErrors([])
      setIsValid(true)
      onValidationChange?.(true, [])
      return
    }

    setIsValidating(true)

    try {
      // 模拟异步验证（可以替换为实际的API调用）
      await new Promise(resolve => setTimeout(resolve, 100))
      
      const result = validateSQLAdvanced(sql)
      setErrors(result.errors)
      setIsValid(result.valid)
      onValidationChange?.(result.valid, result.errors)
    } catch (error) {
      console.error('SQL验证失败:', error)
      setErrors([{
        type: 'error',
        message: '验证过程中发生错误',
        suggestion: '请检查SQL语句格式'
      }])
      setIsValid(false)
      onValidationChange?.(false, errors)
    } finally {
      setIsValidating(false)
    }
  }

  // 手动验证
  const handleManualValidation = () => {
    performValidation()
  }

  // 自动验证
  useEffect(() => {
    if (autoValidate) {
      const timer = setTimeout(() => {
        performValidation()
      }, 500) // 防抖

      return () => clearTimeout(timer)
    }
  }, [sql, autoValidate])

  // 获取错误统计
  const errorStats = {
    errors: errors.filter(e => e.type === 'error').length,
    warnings: errors.filter(e => e.type === 'warning').length,
    infos: errors.filter(e => e.type === 'info').length,
  }

  // 获取整体状态
  const getOverallStatus = () => {
    if (errorStats.errors > 0) return 'error'
    if (errorStats.warnings > 0) return 'warning'
    if (errorStats.infos > 0) return 'info'
    return 'success'
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'error': return <ExclamationCircleOutlined />
      case 'warning': return <WarningOutlined />
      case 'info': return <InfoCircleOutlined />
      default: return <CheckCircleOutlined />
    }
  }

  const getStatusMessage = () => {
    if (isValidating) return 'SQL验证中...'
    if (errorStats.errors > 0) return `发现 ${errorStats.errors} 个错误`
    if (errorStats.warnings > 0) return `发现 ${errorStats.warnings} 个警告`
    if (errorStats.infos > 0) return `${errorStats.infos} 个建议`
    return 'SQL语法正确'
  }

  if (!sql.trim() && autoValidate) {
    return null
  }

  const overallStatus = getOverallStatus()

  return (
    <div style={{ margin: '8px 0' }}>
      {/* 状态概览 */}
      <Alert
        type={overallStatus as any}
        icon={getStatusIcon(overallStatus)}
        message={
          <Space>
            <span>{getStatusMessage()}</span>
            {errorStats.errors > 0 && <Tag color="red">{errorStats.errors} 错误</Tag>}
            {errorStats.warnings > 0 && <Tag color="orange">{errorStats.warnings} 警告</Tag>}
            {errorStats.infos > 0 && <Tag color="blue">{errorStats.infos} 建议</Tag>}
            {!autoValidate && (
              <Button
                size="small"
                icon={<BugOutlined />}
                onClick={handleManualValidation}
                loading={isValidating}
              >
                验证SQL
              </Button>
            )}
          </Space>
        }
        showIcon
        style={{ marginBottom: errors.length > 0 && showDetails ? 8 : 0 }}
      />

      {/* 详细错误信息 */}
      {errors.length > 0 && showDetails && (
        <Collapse size="small" ghost>
          <Panel
            header={`查看详细信息 (${errors.length} 项)`}
            key="details"
          >
            <div style={{ maxHeight: 200, overflowY: 'auto' }}>
              {errors.map((error, index) => (
                <div
                  key={index}
                  style={{
                    padding: '8px 12px',
                    marginBottom: 8,
                    background: error.type === 'error' ? '#fff2f0' : 
                               error.type === 'warning' ? '#fffbe6' : '#f6ffed',
                    border: `1px solid ${
                      error.type === 'error' ? '#ffccc7' :
                      error.type === 'warning' ? '#ffe58f' : '#b7eb8f'
                    }`,
                    borderRadius: 4,
                  }}
                >
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Space>
                      {error.type === 'error' && <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />}
                      {error.type === 'warning' && <WarningOutlined style={{ color: '#faad14' }} />}
                      {error.type === 'info' && <InfoCircleOutlined style={{ color: '#1890ff' }} />}
                      <Text strong>{error.message}</Text>
                      {error.line && (
                        <Tag size="small">行 {error.line}</Tag>
                      )}
                    </Space>
                    {error.suggestion && (
                      <Paragraph
                        style={{
                          margin: 0,
                          fontSize: 12,
                          color: '#666',
                          fontStyle: 'italic'
                        }}
                      >
                        💡 {error.suggestion}
                      </Paragraph>
                    )}
                  </Space>
                </div>
              ))}
            </div>
          </Panel>
        </Collapse>
      )}
    </div>
  )
}

export default SQLValidator